
interface JNFrameTimeHandler{
    id:number,
    handler:Function,
    timeout:number,
    totalTime:number,
    isInterval?:boolean
}

//帧同步定时器
export default class JNFrameTime{

    static _instance: JNFrameTime;
    
    static getInstance(): JNFrameTime {
        if(JNFrameTime._instance)
            return JNFrameTime._instance;
        return JNFrameTime._instance = new JNFrameTime();
    }

    static deleteInstance(){
        JNFrameTime._instance = null;
    }

    id:number;
    handlers:JNFrameTimeHandler[] = [];

    //设置定时器
    setTimeout(handler:Function,timeout:number = 0):number{
        return this.handlers.push({id:this.id++,handler:handler,timeout:timeout,isInterval:false,totalTime:timeout});
    }
    setInterval(handler:Function,timeout:number = 0):number{
        return this.handlers.push({id:this.id++,handler:handler,timeout:timeout,isInterval:true,totalTime:timeout});
    }
    
    //清除定时器
    clearTimeout(id:number):void{
        for (let index = 0; index < this.handlers.length; index++) {
            const handler = this.handlers[index];
            if(handler.id === id){
                this.handlers.splice(index,1);
                index--;
            }
        }
    }

    onUpdate(dt:number){
        
        for (let index = 0; index < this.handlers.length; index++) {
            const handler = this.handlers[index];
            handler.timeout-=dt;
            if(handler.timeout <= 0){
                if(!handler.isInterval){
                    this.handlers.splice(index,1);
                    index--;
                }else{
                    handler.timeout = handler.totalTime;
                }
                handler.handler();
            }
        }

    }

}

